﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
public partial class RFCompose : System.Web.UI.Page
{
    RegistrationData reg = new RegistrationData();
    Communication cs = new Communication();
    DataSet ds = null;
    public string body = string.Empty, Subject = string.Empty, From = string.Empty, To = string.Empty, Cc = string.Empty;
    string UserType = string.Empty; string recieversList = string.Empty,action=string.Empty;
    int UserID = 0, IsPaid = 0, UserTypeID = 0, result = 0;
    public int MessageID = 0;
   public const string svgDataKey = "svgDataKey";
   SendEmails auto = new SendEmails();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session[svgDataKey] = null;

            if (Request.QueryString["Silpath"] != null)
            {
                Session[svgDataKey] = Convert.ToString(Request.QueryString["Silpath"]);
            }
             if (Request.QueryString["MessageID"] != null)
            {
                try
                {
                    MessageID = Convert.ToInt32(Request.QueryString["MessageID"]);
                    if (Request.QueryString["mBox"] != null)
                    {
                        if (Session["User"] != null)
                        {
                            reg = (RegistrationData)Session["User"];
                            cs.UserID = reg.UserID;
                            cs.CommunicationID = Convert.ToInt32(Request.QueryString["mBox"]);
                            cs.MarkAsRead_Message();
                        }
                    }
                    if (Request.QueryString["Action"] != null)
                    {
                        action = Convert.ToString(Request.QueryString["Action"]).ToLower();
                        if (action != string.Empty)
                        {
                            if (action == "forward" || action == "reply")
                            {
                                BindMessage(MessageID);
                                Body(MessageID);
                                //if (body == string.Empty || body == "")
                                //    txtbody.Content = "";
                                ////txtbody.Content = "<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><hr/><hr/><br/>";
                                //else txtbody.Content = "<br/><br/><br/><br/><br/><br/><br/><hr/><hr/><br/>" + body;
                                if (action == "reply")
                                {
                                    txtToList.Text = From;
                                    txtCc.Text = Cc;
                                    txtSubject.Text = "Re: " + Subject;
                                    this.Title = "Reply";
                                }
                                else
                                {
                                    txtSubject.Text = "Fw: " + Subject;
                                    this.Title = "Forward";
                                }
                            }
                            else Response.Redirect(Common.ErrorPage);
                        }
                        else Response.Redirect(Common.ErrorPage);
                    }
                    else Response.Redirect(Common.ErrorPage);
                }
                catch (Exception ex)
                {
                    Response.Redirect(Common.ErrorPage);
                }

            }
            else Response.Redirect("MyAccount.aspx");

             BindUsers();
        }

        //if (!string.IsNullOrEmpty(Convert.ToString(Session[svgDataKey])))
        //{
        //    lnkOpenReviewer.Visible = true;
        //    lnkOpenReviewer.HRef = "./Attach_Open.aspx?Silpath=" + Convert.ToString(Session[svgDataKey]);
        //}
    }

    void BindMessage(int ID)
    {
        if (Session["User"] != null)
        {
            ds = new DataSet();
            reg = (RegistrationData)Session["User"];
            cs.UserID = reg.UserID;
            cs.MessageID = ID;
            ds = cs.Select_Messages();
            if (ds != null)
            {
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataRow dr = ds.Tables[0].Rows[0];
                        if (!string.IsNullOrEmpty(Convert.ToString(dr["Sender"])))
                            From = Convert.ToString(dr["Sender"]);
                        if (!string.IsNullOrEmpty(Convert.ToString(dr["Subject"])))
                        {
                            if (Convert.ToString(dr["Subject"]) != "No Subject")
                                Subject = Convert.ToString(dr["Subject"]);
                        }
                        if (!string.IsNullOrEmpty(Convert.ToString(dr["Message"])))
                            body = Convert.ToString(dr["Message"]);
                        if (!string.IsNullOrEmpty(Convert.ToString(dr["To"])))
                            To = Convert.ToString(dr["To"]);
                        if (!string.IsNullOrEmpty(Convert.ToString(dr["CC"])))
                            Cc = Convert.ToString(dr["CC"]);
                    
                        if (!string.IsNullOrEmpty(Convert.ToString(dr["SilPath"])))
                        {
                            ViewState[svgDataKey] = Convert.ToString(dr["SilPath"]);
                             
                        }
                        else
                        {
                            ViewState[svgDataKey] = null;  
                        }

                        //if()
                        gvNewFiles.DataSource = ds.Tables[1];
                        gvNewFiles.DataBind();
                    }
                    else AlertMessage();
                }
                else AlertMessage();
            }
            else AlertMessage();
        }
    }

    void Body(int ID)
    {
        System.Text.StringBuilder sbBody=new System.Text.StringBuilder();
        //sbBody.Append("<div style=' border:none;border-left:2px solid #464EEA;'><p style='margin-bottom:5px;'><label style='width:85px; float:left;  text-transform:capitalize; font-weight:bold; font-size:15px;text-align:right;'>From:</label> <label style=' margin-left:5px;'>" + From + " </label></p>" +
        //                    "<p  style='margin-bottom:5px;'><label style='width:85px; float:left;  text-transform:capitalize; font-weight:bold; font-size:15px; text-align:right;'>cc:</label> <label style=' margin-left:5px;'>" + Cc + "</label></p></div>");

        Common.To = To;
        Common.From = From;
        Common.Subject = Subject;
        Common.CC = Cc;
        Common.Body = body;
        if (ViewState[svgDataKey] != null)
        {
            Common.AttachmentPath = "./ALM-Attach_Open.aspx?Silpath=" + Crypto.EncryptStringAES(ID.ToString());
        }
        else
        {
            Common.AttachmentPath = string.Empty;
        }

        Page page = new Page();
        StringWriter sw = new StringWriter();
        UserControl control = (UserControl)page.LoadControl("~/Alumini/UserControls/ALM-RFContent.ascx");
        page.Controls.Add(control);

        HttpContext.Current.Server.Execute(page, sw, false);
        divOldMessage.InnerHtml = sw.ToString();
       // txtbody.Content = sw.ToString();

    }
    
    void AlertMessage()
    {
        //string script = string.Format("alert('You are not authorized to view this message')");
        //ClientScript.RegisterClientScriptBlock(this.GetType(), "alertScript", script, true);
        if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["mbox"])))
            Response.Redirect("ALM-InboxMessageList.aspx");
        else
            Response.Redirect("ALM-SentMessages.aspx");
    }

    void BindUsers()
    {
        if (Session["User"] != null)
        {
            ds = new DataSet();
            reg = (RegistrationData)Session["User"];
            UserTypeID = reg.UserTypeID;
            UserID = reg.UserID;
            cs.UserID = UserID;
            //ds = cs.Select_UserList();
            ////chkLstUsers.DataSource = ds;
            ////chkLstUsers.DataTextField = "FirstName";
            ////chkLstUsers.DataValueField = "UserID";
            ////chkLstUsers.DataBind();
            //lstUsergroups.Items.Clear();
            //lstUsergroups.DataSource = ds;
            //lstUsergroups.DataBind();


            //lstCC.Items.Clear();
            //lstCC.DataSource = ds;
            //lstCC.DataBind();

            string[] users1 = Convert.ToString(txtToList.Text.Replace(" ", "")).Split(new char[] { ',' });
            for (int i = 0; i < lstUsergroups.Items.Count; i++)
            {
                CheckBox chk = lstUsergroups.Items[i].FindControl("chkUser") as CheckBox;
                if (chk != null)
                {
                    foreach (string user in users1)
                    {
                        if (user != "" && user != string.Empty)
                        {
                            if (chk.Text == user)
                            {
                                chk.Checked = true;
                                break;
                            }
                        }
                    }
                }
            
            }


            if (txtCc.Text != string.Empty)
            {
                string[] users = Convert.ToString(txtCc.Text.Replace(" ", "")).Split(new char[] { ',' });
                for (int i = 0; i < lstCC.Items.Count; i++)
                {
                    CheckBox chk = lstCC.Items[i].FindControl("chkUser") as CheckBox;
                    if (chk != null)
                    {
                        foreach (string user in users)
                        {
                            if (user != "" && user != string.Empty)
                            {
                                if (chk.Text == user)
                                {
                                    chk.Checked = true;
                                    break;
                                }
                            }
                        }
                    }

                }
            }
        }
        InsertData();
    }
    
    private void BindCheckALL(ListView lvchkAll, string chkID, object sender)
    {
        CheckBox chkHeader = sender as CheckBox;
        for (int i = 0; i < lvchkAll.Items.Count; i++)
        {
            CheckBox chk = lvchkAll.Items[i].FindControl(chkID) as CheckBox;
            chk.Checked = chkHeader.Checked;
        }
    }

    protected void btnAddSelected_Click(object sender, EventArgs e)
    {
        InsertData();
        //string script = string.Format("javascript:$find('ModalPopupExtender1').hide();");
        //ScriptManager.RegisterStartupScript(this, this.GetType(), "alertScript", script, true);
        ModalPopupExtender1.Hide();
    }


    private void InsertData()
    {
        string UserTo = string.Empty, UserCc = string.Empty;

        ViewState["UserTo"] = AddUser_ToText(lstUsergroups, txtToList, UserTo);

        ViewState["UserCc"] = AddUser_ToText(lstCC, txtCc, UserCc);
    }

    string AddUser_ToText(ListView lst, TextBox txt, string List)
    {
        txt.Text = string.Empty;
        List = string.Empty;
        foreach (Control var in lst.Controls)
        {
            if (var.HasControls())
            {
                foreach (Control varInner in var.Controls)
                {
                    CheckBox ch = (CheckBox)varInner.FindControl("chkUser");
                    if (ch != null)
                    {
                        if (ch.Checked)
                        {
                            txt.Text += ch.Text + ",";
                            Label lbl = (Label)varInner.FindControl("lblUserID");
                            List += lbl.Text + ",";
                        }
                    }
                }
            }
        }


        if (txt.Text.Length > 1)
        {
            txt.Text = txt.Text.Remove(txt.Text.Trim().Length - 1, 1);
        }
        return List;
    }


    public void chkuserAll_CheckedChanged(object sender, EventArgs e)
    {
        BindCheckALL(lstUsergroups, "chkUser", sender);
        ModalPopupExtender1.Show();
    }


    public void chklstccuserAll_CheckedChanged(object sender, EventArgs e)
    {
        BindCheckALL(lstCC, "chkUser", sender);
        ModalPopupExtender1.Show();
    }



    protected void btnsendmsg_Click(object sender, EventArgs e)
    {
        if (Session["User"] != null)
        {
            reg = (RegistrationData)Session["User"];
            //cs.HasAttachment = hasAttachment();
            cs.HasAttachment = 0;
            UserID = reg.UserID;
            cs.SenderID = UserID;
            cs.Subject = txtSubject.Text;
            string Name = reg.FirstName;

            cs.Body =txtbody.Content+"<hr  style='margin-top:0px;' /> "+divOldMessage.InnerHtml ;
            // cs.GroupKey = reg.RandomString(5); 

            if (!object.Equals(Session[svgDataKey], null))
                //if (!object.Equals(Session[svgDataKey], null) || !object.Equals(ViewState[svgDataKey], null))
            {
                if (!string.IsNullOrEmpty(Convert.ToString(Session[svgDataKey])))
                {
                    cs.SilPath = Convert.ToString(Session[svgDataKey]);
                }
                //else if (!string.IsNullOrEmpty(Convert.ToString(ViewState[svgDataKey])))
                //{
                //    cs.SilPath = Convert.ToString(ViewState[svgDataKey]);
                //}
            }
            if (ViewState["UserTo"] != null)
            {
                cs.IsCC = 0;
                recieversList = Convert.ToString(ViewState["UserTo"]).Replace(" ", "");
                if (recieversList != "" && recieversList != string.Empty)
                {
                    string[] users = recieversList.Split(new char[] { ',' });
                    foreach (string user in users)
                    {
                        if (user != "" && user != string.Empty)
                        {
                            cs.ReceiverID = Convert.ToInt32(user);
                            cs.MessageID = MessageID;
                            MessageID = cs.SendMessages();
                            auto.SendEmail(Name, cs.ReceiverID);
                        }
                    }
                }
            }
            if (ViewState["UserCc"] != null)
            {
                cs.IsCC = 1;
                recieversList = Convert.ToString(ViewState["UserCc"]).Replace(" ", "");
                if (recieversList != "" && recieversList != string.Empty)
                {
                    string[] users = recieversList.Split(new char[] { ',' });
                    foreach (string user in users)
                    {
                        if (user != "" && user != string.Empty)
                        {
                            cs.ReceiverID = Convert.ToInt32(user);
                            cs.MessageID = MessageID;
                            MessageID = cs.SendMessages();
                            auto.SendEmail(Name, cs.ReceiverID);
                        }
                    }
                }
            }
            if (MessageID > 0)
            {
                SaveAttachments(MessageID);
            }
            Response.Redirect("ALM-MessageSent.aspx");
        }
    }

    string FileType = string.Empty, FileName = string.Empty;
    int hasAttachment()
    {
        int HasAttach = 0;
        HttpFileCollection hfc = Request.Files;
        if (hfc.Count > 0)
        {
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                    HttpPostedFile FileData = hpf;
                    long FileLength = hpf.ContentLength;
                    if (FileLength > 0)
                    {
                        //FileName = System.IO.Path.GetFileName(hpf.FileName);
                        //FileType = System.IO.Path.GetExtension(FileName).ToLower();
                        // if (FileType == ".docx" || FileType == ".doc" || FileType == ".pdf" || FileType == ".rtf" || FileType == ".txt" || FileType == ".jpg" || FileType == ".gif" || FileType == ".png" || FileType == ".bmp" || FileType == ".xls" || FileType == ".xlsx" || FileType == ".ppt" || FileType == ".pptx")
                        {
                            HasAttach = 1;
                            return HasAttach;
                        }
                        //else
                        {

                        }
                    }
                }
            }

        }
        for (int i = 0; i < gvNewFiles.Items.Count; i++)
        {
            CheckBox chk = gvNewFiles.Items[i].FindControl("chkAttach") as CheckBox;
            if (chk != null)
                if (chk.Checked)
                    return 1;
        }

        return HasAttach;
    }

    BusinessLogic bsLogic = new BusinessLogic();
    void SaveAttachments(int MessageID)
    {
        string path = string.Empty;
        cs.MessageID = MessageID;
        HttpFileCollection hfc = Request.Files;
        if (hfc.Count > 0)
        {
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                    HttpPostedFile FileData = hpf;
                    long FileLength = hpf.ContentLength;
                    if (FileLength > 0)
                    {
                        FileName = System.IO.Path.GetFileName(hpf.FileName);
                        FileName = bsLogic.ValidateImageName("~/Uploads/", FileName);
                        path = Server.MapPath("~/Uploads/") + FileName;
                        FileData.SaveAs(path);
                        cs.SaveAttachment_Path(path, FileName);
                    }
                }
            }

        }

        for (int i = 0; i < gvNewFiles.Items.Count; i++)
        {
            CheckBox chk = gvNewFiles.Items[i].FindControl("chkAttach") as CheckBox;
            if (chk.Checked)
            {
                LinkButton lnkFileName = gvNewFiles.Items[i].FindControl("lbtnFiles") as LinkButton;
                if (lnkFileName != null)
                {
                    FileName = lnkFileName.Text;
                    path = Server.MapPath("~/Uploads/") + FileName;
                    cs.SaveAttachment_Path(path, FileName);
                }
            }
        }
    }

    protected void gvNewFiles_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "downloadFile":
                string strFolder = "~/Uploads/";
                string filePath = Path.Combine(strFolder, e.CommandArgument.ToString());
                DownloadFile(filePath);
                break;
        }
    }

    public void DownloadFile(string filePath)
    {
        if (File.Exists(Server.MapPath(filePath)))
        {
            string strFileName = Path.GetFileName(filePath).Replace(" ", "%20");
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
            Response.Clear();
            Response.WriteFile(Server.MapPath(filePath));
            Response.End();
        }
    }

    protected void lnkOpenReviewer_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Convert.ToString(Session[svgDataKey])))
        {
            string url = Session[svgDataKey].ToString();
            string script = "window.open('" + url + "','')";
            if (!ClientScript.IsClientScriptBlockRegistered("NewWindow"))
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "NewWindow", script, true);
            } 
        }
    }
}